<template>
  <div id="orders">
    <el-card shadow="always">
      <!-- 条件查询表单 -->
      <el-form :inline="true" size="medium"  class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" plain @click="addOrder">添加订单</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="onDeleteOrders">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="orders"
                style="width: 100%"
                @selection-change="SelectedChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column label="订单ID" align="center" prop="orderIid" width="180"/>
        <el-table-column label="用户ID" align="center" prop="userId"/>
        <el-table-column label="金额" align="center" prop="amount"/>
        <el-table-column label="下单时间" align="center" prop="orderTime"/>
        <el-table-column label="状态" align="center" prop="status"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="onEditOrder(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="onDeleteOrders(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 对话框 -->
    <el-dialog :title="titles" :visible.sync="dialogFormVisible">
      <el-form :model="order" :rules="formRules" ref="ruleForm">

        <!-- 用户ID -->
        <el-form-item label="用户ID" :label-width="formLabelWidth" prop="userId">
          <el-input v-model="order.userId" auto-complete="off"></el-input>
        </el-form-item>

        <!-- 金额 -->
        <el-form-item label="金额" :label-width="formLabelWidth" prop="amount">
          <el-input v-model="order.amount" auto-complete="off" type="number"></el-input>
        </el-form-item>

        <!-- 下单时间 -->
        <el-form-item label="下单时间" :label-width="formLabelWidth" prop="orderTime">
          <el-date-picker v-model="order.orderTime" type="datetime" placeholder="选择下单时间" :picker-options="{ disabledDate(time) { return time.getTime() > Date.now() } }"></el-date-picker>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="order.status" placeholder="请选择订单状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="已完成" value="已完成"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入相关 API
import orderApi from "@/api/order"

export default {
  data() {
    return {
      orders: [],                // 订单列表
      selectedId: [],           // 被选中的集合id
      selectedList: [],         // 被选中的集合
      currentPage: 1,           // 当前页码
      itemsPerPage: 5,          // 每页条数
      totalRecords: 100,        // 总记录数
      dialogFormVisible: false, // 对话框显示状态
      titles: "添加订单",       // 对话框标题
      order: {                   // 订单对象
        orderIid: null,          // 订单ID
        userId: "",              // 用户ID
        amount: null,            // 金额
        orderTime: "",           // 下单时间
        status: ""               // 状态
      },
      formRules: {
        userId: [{required: true, message: "请输入用户ID", trigger: "blur"}],
        amount: [{required: true, message: "请输入金额", trigger: "blur"}],
        orderTime: [{required: true, message: "请选择下单时间", trigger: "blur"}],
        status: [{required: true, message: "请选择订单状态", trigger: "blur"}]
      },
      formLabelWidth: "120px"  // 表单项的标签宽度
    };
  },
  created() {
    this.getAllOrders();       // 初始化查询数据
  },
  methods: {
    // 查询所有订单
    async getAllOrders() {
      const {data: res} = await orderApi.findAllOrders()
      if (res.code === 200) {
        this.orders = res.data.list
      }
    },
    // 触发编辑订单
    onEditOrder(index, row) {
      this.titles = "编辑订单";
      this.order = Object.assign({}, row);  // 使用 Object.assign 进行浅拷贝，避免直接引用
      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate(); // 清除校验
        }
      });
      this.dialogFormVisible = true;
    },
    // 触发显示添加订单表单
    addOrder() {
      this.titles = '添加订单'
      this.order = {}  // 清空数据
      this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.clearValidate(); // 清除校验
        }
      });
      this.dialogFormVisible = true
    },
    // 保存订单
    async saveOrder() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let url = "/order/add"; // 默认添加订单
          let method = "post";   // 默认 POST 方法
          if (this.order.orderIid) {
            url = "/order/update";
            method = "put";
          }
          try {
            const {data: res} = await orderApi.saveOrder(url, this.order, method);
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                onClose: () => {
                  this.dialogFormVisible = false;
                  this.getAllOrders();  // 重新查询订单列表
                }
              });
            } else {
              this.$message({
                type: 'error',
                message: res.message
              });
            }
          } catch (error) {
            console.error("保存订单失败:", error);
          }
        } else {
          console.log("表单验证失败，请检查输入");
          return false;
        }
      });
    },
    // 删除订单
    onDeleteOrders(index, row) {
      this.selectedId = []
      if (row) {
        this.selectedId.push(row.orderIid)
      } else {
        this.selectedId = this.selectedList.map(m => m.orderIid)
      }
      this.$confirm(`是否真的要删除订单ID为${this.selectedId}的订单吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        orderApi.deleteOrder(this.selectedId)
            .then(({data: res}) => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    _this.getAllOrders();  // 重新查询订单列表
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 选择订单改变时
    SelectedChange(val) {
      this.selectedList = val;
    }
  },
  // computed: {
  //   formattedOrderTime() {
  //     // 使用 moment 格式化日期
  //     return moment(this.orderTime).format('YYYY-MM-DD HH:mm:ss');
  //   }}

};
</script>

<style>
#orders {
  display: flex;
  justify-content: center;
}
.el-card {
  width: 90%;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
